package com.wts.exam.service.impl;

import com.wts.exam.domain.Paper;
import com.wts.exam.domain.PaperAnswer;
import com.wts.exam.domain.PaperCard;
import com.wts.exam.domain.Room;
import com.wts.exam.domain.SubjectVersion;
import com.wts.exam.domain.ex.ChapterUnit;
import com.wts.exam.domain.ex.PaperUnit;
import com.wts.exam.domain.ex.SubjectUnit;
import com.wts.exam.domain.ex.TipType;
import com.farm.core.time.TimeTool;

import org.apache.log4j.Logger;

import com.wts.exam.dao.PaperDaoInter;
import com.wts.exam.dao.PaperanswerDaoInter;
import com.wts.exam.dao.PapercardDaoInter;
import com.wts.exam.dao.SubjectversionDaoInter;
import com.wts.exam.service.PapercardServiceInter;
import com.wts.exam.service.RoomServiceInter;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：答题卡服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class PapercardServiceImpl implements PapercardServiceInter {
	@Resource
	private PaperanswerDaoInter paperanswerDaoImpl;
	@Resource
	private PapercardDaoInter papercardDaoImpl;
	@Resource
	private RoomServiceInter roomServiceImpl;
	@Resource
	private PaperDaoInter paperDaoImpl;
	@Resource
	private SubjectversionDaoInter subjectversionDaoImpl;
	private static final Logger log = Logger.getLogger(PapercardServiceImpl.class);

	@Override
	@Transactional
	public PaperCard insertPapercardEntity(PaperCard entity, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		// entity.setCuser(user.getId());
		// entity.setCtime(TimeTool.getTimeDate14());
		// entity.setCusername(user.getName());
		// entity.setEuser(user.getId());
		// entity.setEusername(user.getName());
		// entity.setEtime(TimeTool.getTimeDate14());
		// entity.setPstate("1");
		return papercardDaoImpl.insertEntity(entity);
	}

	@Override
	@Transactional
	public PaperCard editPapercardEntity(PaperCard entity, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		PaperCard entity2 = papercardDaoImpl.getEntity(entity.getId());
		// entity2.setEuser(user.getId());
		// entity2.setEusername(user.getName());
		// entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setPcontent(entity.getPcontent());
		entity2.setEndtime(entity.getEndtime());
		entity2.setPstate(entity.getPstate());
		entity2.setStarttime(entity.getStarttime());
		entity2.setAdjudgetime(entity.getAdjudgetime());
		entity2.setAdjudgeuser(entity.getAdjudgeuser());
		entity2.setPoint(entity.getPoint());
		entity2.setUserid(entity.getUserid());
		entity2.setRoomid(entity.getRoomid());
		entity2.setPaperid(entity.getPaperid());
		entity2.setId(entity.getId());
		papercardDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deletePapercardEntity(String id, LoginUser user) {
		// TODO 自动生成代码,修改后请去除本注释
		papercardDaoImpl.deleteEntity(papercardDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public PaperCard getPapercardEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return papercardDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createPapercardSimpleQuery(DataQuery query) {
		// TODO 自动生成代码,修改后请去除本注释
		DataQuery dbQuery = DataQuery.init(query, "WTS_PAPER_CARD",
				"ID,PCONTENT,ENDTIME,PSTATE,STARTTIME,ADJUDGETIME,ADJUDGEUSER,POINT,USERID,ROOMID,PAPERID");
		return dbQuery;
	}

	@Override
	@Transactional
	public PaperCard creatOrGetPaperCard(String paperid, String roomId, LoginUser currentUser) {
		// 房间是否超时，是否有答题权限
		Room room = roomServiceImpl.getRoomEntity(roomId);
		if (!roomServiceImpl.isLiveTimeRoom(room)) {
			throw new RuntimeException("该房间不可用，未到答题时间!");
		}
		if (currentUser == null) {
			throw new RuntimeException("请先登陆系统!");
		}
		if (!roomServiceImpl.isUserAbleRoom(room.getId(), currentUser)) {
			throw new RuntimeException("当前用户无进入权限!");
		}

		Paper paper = paperDaoImpl.getEntity(paperid);
		if (paper == null) {
			throw new RuntimeException("该试卷不存在!id:" + paperid);
		}
		List<PaperCard> cards = papercardDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("PAPERID", paperid, "=")).add(new DBRule("USERID", currentUser.getId(), "="))
				.add(new DBRule("ROOMID", roomId, "=")).toList());
		// 查询答题卡
		if (cards.size() > 0) {
			PaperCard card = cards.get(0);
			String endTime = card.getEndtime();
			if (TimeTool.getTimeDate14().compareTo(endTime) >= 0) {
				card.setPstate("3");
				papercardDaoImpl.editEntity(card);
			}
			return card;
		} else {// 创建答题卡
			String startTime = null;
			String endTime = null;
			{
				SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
				startTime = TimeTool.getTimeDate14();
				Date date;
				try {
					date = format.parse(startTime);
				} catch (ParseException e) {
					throw new RuntimeException("时间格式化错误！");
				}
				Date endtime = TimeTool.getTimeDate12ForMinute(room.getTimelen(), date);
				endTime = format.format(endtime);
			}
			{
				PaperCard card = new PaperCard();
				// card.setAdjudgetime(adjudgetime);
				// card.setAdjudgeuser(adjudgeuser);
				card.setStarttime(startTime);
				card.setEndtime(endTime);
				card.setPaperid(paperid);
				// card.setPcontent(pcontent);
				// card.setPoint(point);
				card.setPstate("1");
				card.setRoomid(roomId);
				card.setUserid(currentUser.getId());
				card = papercardDaoImpl.insertEntity(card);
				return card;
			}
		}
	}

	@Override
	@Transactional
	public PaperCard loadPaperCard(String paperid, String roomid, LoginUser currentUser) {
		List<PaperCard> cards = papercardDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("PAPERID", paperid, "=")).add(new DBRule("USERID", currentUser.getId(), "="))
				.add(new DBRule("ROOMID", roomid, "=")).toList());
		if (cards.size() > 0) {
			PaperCard card = cards.get(0);
			String endTime = card.getEndtime();
			if (TimeTool.getTimeDate14().compareTo(endTime) >= 0 && card.getPstate().equals("1")) {
				card.setPstate("3");
				papercardDaoImpl.editEntity(card);
			}
			return cards.get(0);
		}
		return null;
	}

	@Override
	@Transactional
	public boolean savePaperCardVal(String paperid, String roomid, String versionid, String answerid, String value,
			LoginUser currentUser) {
		// 删除已有的答案
		PaperCard card = loadPaperCard(paperid, roomid, currentUser);
		if (card == null) {
			throw new RuntimeException("答题卡获取失败：答卷" + paperid + "/房间" + roomid);
		}
		paperanswerDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("CARDID", card.getId(), "="))
				.add(new DBRule("VERSIONID", versionid, "=")).add(new DBRule("ANSWERID", answerid, "=")).toList());

		List<PaperAnswer> answers = paperanswerDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("CARDID", card.getId(), "=")).add(new DBRule("VERSIONID", versionid, "=")).toList());
		// 添加新的答案
		PaperAnswer answer = new PaperAnswer();
		answer.setAnswerid(answerid);
		answer.setCardid(card.getId());
		answer.setCtime(TimeTool.getTimeDate14());
		answer.setCuser(currentUser.getId());
		answer.setPstate("1");
		answer.setValstr(value);
		answer.setVersionid(versionid);
		answer = paperanswerDaoImpl.insertEntity(answer);
		answers.add(answer);
		// ---------------------------------------------
		SubjectVersion version = subjectversionDaoImpl.getEntity(versionid);
		TipType tiptype = TipType.getTipType(version.getTiptype());
		return tiptype.getHandle().isHaveAnswer(answers);
	}

	@Override
	@Transactional
	public void finishExam(String cardId, LoginUser currentUser) {
		PaperCard card = papercardDaoImpl.getEntity(cardId);
		if (!card.getUserid().equals(currentUser.getId())) {
			throw new RuntimeException("答题卡用户非当前用户!");
		}
		if (!card.getPstate().equals("1")) {
			return;
		}
		card.setEndtime(TimeTool.getTimeDate14());
		card.setPstate("2");
		papercardDaoImpl.editEntity(card);
	}

	@Override
	@Transactional
	public void loadCardVal(PaperUnit paper, PaperCard card) {
		// 取得所有答题卡的值
		List<PaperAnswer> answerVals = paperanswerDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("CARDID", card.getId(), "=")).toList());
		if (answerVals.size() <= 0) {
			return;
		}
		Map<String, List<PaperAnswer>> answerValsMap = new HashMap<>();
		for (PaperAnswer answer : answerVals) {
			List<PaperAnswer> panswers = answerValsMap.get(answer.getVersionid());
			if (panswers == null) {
				panswers = new ArrayList<>();
				answerValsMap.put(answer.getVersionid(), panswers);
			}
			panswers.add(answer);
		}
		// 填充道试卷中
		for (ChapterUnit chapter1 : paper.getChapters()) {
			// 第一層章節
			List<SubjectUnit> subjects = chapter1.getSubjects();
			loadSubjectVal(subjects, answerValsMap);
			for (ChapterUnit chapter2 : chapter1.getChapters()) {
				// 第二層章節
				List<SubjectUnit> subjects2 = chapter2.getSubjects();
				loadSubjectVal(subjects2, answerValsMap);
				for (ChapterUnit chapter3 : chapter2.getChapters()) {
					// 第三層章節
					List<SubjectUnit> subjects3 = chapter3.getSubjects();
					loadSubjectVal(subjects3, answerValsMap);
				}
			}
		}
	}

	/**
	 * 将考题值填充到题目中
	 * 
	 * @param subjects
	 *            试题序列
	 * @param answerVals
	 *            map<试题版本id,用户答案序列>
	 */
	private void loadSubjectVal(List<SubjectUnit> subjects, Map<String, List<PaperAnswer>> answerVals) {
		for (SubjectUnit nuit : subjects) {
			nuit.getTipType().getHandle().loadVal(nuit, answerVals.get(nuit.getVersion().getId()));
		}
	}

}
